#include "ds18b20.h"


int ds18b20_get_temperature(float *t)
{
      DIR             *dirp;
       struct dirent   *direntp;
        char            path[1024];
        int             fd;
          int             rv;
           char            buffer[BUF_SIZE];
            char            *result;

    if((dirp = opendir(PATH)) == NULL)
    {
		printf("Failed to open the destination directory: %s\n",strerror(errno));
		return -1;
	}

	while((direntp = readdir(dirp)) != NULL)
	{
		if(strstr(direntp->d_name,"28-") != NULL)
		{
			break;
		}
	}
	
	if(direntp == NULL)
	{
		printf("Failed to find the destination directory: 28-*** .\n");
		closedir(dirp);
        return -2;
	}
    
    memset(path,0,sizeof(path));
    strcat(path,PATH);
	strcat(path,direntp->d_name);
	strcat(path,"/w1_slave");
	closedir(dirp);

	if((fd = open(path,O_RDONLY)) < 0)
	{
		printf("Failed to open the destination file.\n");
		return -3;
	}

	memset(buffer,0,sizeof(buffer));
	while((rv = read(fd,buffer,sizeof(buffer))) > 0)
	{	
		
		if((result = strstr(buffer,"t=")) != NULL)
		{
			result = result + 2;
			break;
		}
	}

	if(rv <= 0)
	{
		printf("Failed to read the temperature.\n");
		close(fd);
        return -4;
	}
	
	*t = atof(result)/1000;
    close(fd);
	return 0;
}


#if 0
int main()
{   
    float t;
    ds18b20_get_temperature(&t);
    printf("%f\n",t);
}
#endif 

